package com.fortune.rainshine.common;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.fortune.rainshine.common.utils.StringUtil;
import com.fortune.rainshine.system.service.AuthoritiesService;
import com.fortune.rainshine.system.service.RoleService;
import com.fortune.rainshinecommon.model.system.Authorities;
import com.fortune.rainshinecommon.model.system.Role;
import com.fortune.rainshinecommon.model.system.User;




/**
 * @ClassName: BaseController
 * @Description: Controller基类
 * @author zhangxin
 * @date 2019年3月26日
 */
public class BaseController {
	@Autowired
    @Lazy
    private AuthoritiesService authoritiesService;
	
	@Autowired
    @Lazy
    private RoleService roleService;

    /**
     * 获取当前登录的user
     */
    public User getLoginUser() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            Object object = subject.getPrincipal();
            if (object != null) {
                return (User) object;
            }
        }
        return null;
    }

    /**
     * 获取当前登录的userId
     */
    public Integer getLoginUserId() {
        User loginUser = getLoginUser();
        return loginUser == null ? null : loginUser.getUserId();
    }

    /**
     * 获取当前登录的username
     */
    public String getLoginUserName() {
        User loginUser = getLoginUser();
        return loginUser == null ? null : loginUser.getUsername();
    }
    
    /**
     * 获取当前登录的角色
     */
    public Role getLoginUserRole() {
        User loginUser = getLoginUser();
        return loginUser == null ? null : roleService.getByUserId(loginUser.getUserId()).get(0);
    }
    
    
    /**
     * 获取当前登录用户的的权限
     */
    public Set<String> getLoginUserAuthorities() {
        User loginUser = getLoginUser();
        String authority = null;
        Set<String> permissions = new HashSet<>();
        if(loginUser != null) {
        	List<Authorities> authorities = authoritiesService.listByUserId(loginUser.getUserId());
            for (int i = 0; i < authorities.size(); i++) {
                authority = authorities.get(i).getAuthority();
                if (StringUtil.isNotBlank(authority)) {
                    permissions.add(authority);
                }
            }
        }
        return permissions;
    }

}
